package com.ruoyi.system.controller;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.api.domain.MaterialInfo;
import com.ruoyi.system.service.IMaterialInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 资料信息Controller
 * 
 * @author ruoyi
 * @date 2023-12-04
 */
@RestController
@RequestMapping("/info")
public class MaterialInfoController extends BaseController
{
    @Autowired
    private IMaterialInfoService materialInfoService;

    /**
     * 查询资料信息列表
     */
    @RequiresPermissions("system:info:list")
    @GetMapping("/list")
    public TableDataInfo list(MaterialInfo materialInfo)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            materialInfo.setAppId(user.getAppId());
        }
        startPage();
        List<MaterialInfo> list = materialInfoService.selectMaterialInfoList(materialInfo);
        return getDataTable(list);
    }

    /**
     * 导出资料信息列表
     */
    @RequiresPermissions("system:info:export")
    @Log(title = "资料信息", businessType = BusinessType.GENCODE)
    @GetMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") String ids) throws IOException
    {
        MaterialInfo materialInfo = new MaterialInfo();
        String[] idAry = ids.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id:idAry) {
            idList.add(Long.valueOf(id));
        }
        materialInfo.setIds(idList);
        List<MaterialInfo> list = materialInfoService.selectMaterialInfoList(materialInfo);
        String album = "导出资料";
        byte[] data = this.downloadCode(album,list);
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(album, "UTF8")+".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 获取资料信息详细信息
     */
    @RequiresPermissions("system:info:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(materialInfoService.selectMaterialInfoById(id));
    }

    @GetMapping(value = "/get/{id}")
    public R<MaterialInfo> getMaterialZl(@PathVariable("id") Long id)
    {
        return R.ok(materialInfoService.selectMaterialInfoById(id));
    }

    @GetMapping(value = "/getSize/{size}")
    public R<MaterialInfo> getMaterialZlsize(@PathVariable("size") Long size)
    {
        return R.ok(materialInfoService.selectMaterialInfoBySize(size));
    }

    /**
     * 新增资料信息
     */
    @RequiresPermissions("system:info:add")
    @Log(title = "资料信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MaterialInfo materialInfo)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            materialInfo.setAppId(user.getAppId());
        }
        MaterialInfo param = new MaterialInfo();
        param.setMaterialName(materialInfo.getMaterialName());
        param.setAppId(user.getAppId());
        List<MaterialInfo> list = materialInfoService.selectMaterialInfoList(param);
        if (null!=list&&list.size()>0) {
            return AjaxResult.error("新增资料'" + materialInfo.getMaterialName() + "'失败，资料已存在");
        }
        return toAjax(materialInfoService.insertMaterialInfo(materialInfo));
    }

    /**
     * 修改资料信息
     */
    @RequiresPermissions("system:info:edit")
    @Log(title = "资料信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MaterialInfo materialInfo)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            materialInfo.setAppId(user.getAppId());
        }
        return toAjax(materialInfoService.updateMaterialInfo(materialInfo));
    }

    @PutMapping("/zl")
    public R<Integer> editMaterialZl(@RequestBody MaterialInfo materialInfo)
    {
        return R.ok(materialInfoService.updateMaterialInfo(materialInfo));
    }

    /**
     * 删除资料信息
     */
    @RequiresPermissions("system:info:remove")
    @Log(title = "资料信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(materialInfoService.deleteMaterialInfoByIds(ids));
    }

    private byte[] downloadCode(String albumTitle, List<MaterialInfo> list)throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        DataOutputStream os = null;
        for (MaterialInfo pic : list) {
            if (StringUtils.isEmpty(pic.getUrl())) {
                continue;
            }
            String suffix = FileTypeUtils.getFileType(pic.getUrl());
            String fileName = pic.getAge()+pic.getGradeName()+pic.getSemesterName()+pic.getMaterialName()+"."+suffix;
            File file = new File("");
            try {
                URL url = new URL(pic.getUrl());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                InputStream is = conn.getInputStream();
                file = FileUtils.inputStreamToFile(is, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.exists()) {
                try {
                    assert zip != null;
                    zip.putNextEntry(new ZipEntry(fileName));
                    os = new DataOutputStream(zip);
                    InputStream is = new FileInputStream(file);
                    byte[] b = new byte[100];
                    int length = 0;
                    while ((length = is.read(b)) != -1) {
                        os.write(b, 0, length);
                    }
                    is.close();
                    zip.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        IOUtils.closeQuietly(zip);
        if (os != null) {
            os.flush();
            os.close();
        }
        if (zip != null) {
            zip.close();
        }
        return outputStream.toByteArray();
    }
}
